using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.Entity;
using BarManager.UI.Web.HtmlHelpers;
using BarManager.UI.Web.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace BarManager.UI.Web.Controllers
{
    [Authorize(Users = "admin")]
    public class ZonaController : BaseController<ZonaViewModel, Zona, int>
    {
        public ZonaController(IZonaService service)
            : base(service)
        {
        }

        public override ActionResult Index(int id = 0)
        {
            if (id > 0)
            {
                //- Buscamos la zona
                Zona zona = Service.Get(x => x.Id == id);

                //- Cargamos el modelo
                ZonaViewModel model = new ZonaViewModel
                {
                    Entity = zona,
                    CantidadMesas = zona.Mesas.Count()
                };
                return View(model);
            }
            return View();
        }

        public override ActionResult List(string filter, int page = 1)
        {
            ZonaViewModel model = new ZonaViewModel
             {
                 Entities = Service.Find(x => filter == null || x.Descripcion.Contains(filter))
                                                    .OrderBy(x => x.Descripcion)
                                                    .Skip((page - 1) * PageSize)
                                                    .Take(PageSize),
                 PagingInfo = new PagingInfo
                 {
                     CurrentPage = page,
                     ItemsPerPage = PageSize,
                     TotalItems = Service.Find(x => filter == null || x.Descripcion.Contains(filter)).Count()
                 }
             };
            model.Filter = filter;     
            return View(model);
        }

        public override ActionResult Save(ZonaViewModel model)
        {
            //- Limpiamos mesas 
            model.Entity.Mesas = new List<Mesa>();

            //- Creamos segun la cantidad insertada
            for (int i = 1; i <= model.CantidadMesas; i++)
            {
                Mesa mesa = new Mesa
                {
                    Libre = model.Entity.Habilitada,
                    Nombre = i.ToString()
                };
                model.Entity.Mesas.Add(mesa);
            }

            //- Guardamos o actualizamos
            if (model.Entity.Id > 0)
                ErrorList = this.Service.Update(model.Entity);
            else
                ErrorList = this.Service.Add(model.Entity);
            return ShowError(model, ErrorList);
        }       
    }
}